package threadPractise;

import java.util.concurrent.locks.ReentrantLock;

public class ReenterLock implements Runnable {
    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();
    public int type;
    public ReenterLock(int type){
        this.type = type;
    }
    @Override
    public void run(){
        try{
            if(type==1){
                lock1.lockInterruptibly();
                try {
                    Thread.sleep(500);
                }catch (InterruptedException e){
                }
                lock2.lockInterruptibly();
            }else{
                lock2.lockInterruptibly();
                try {
                    Thread.sleep(500);

                }catch (InterruptedException e){}
                lock1.lockInterruptibly();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            if(lock1.isHeldByCurrentThread())
                lock1.unlock();
            if(lock2.isHeldByCurrentThread())
                lock2.unlock();
            System.out.println(Thread.currentThread().getId()+"�߳��˳�");
        }

    }
    public static void main(String[] args)throws InterruptedException{
        ReenterLock reenterLock1 = new ReenterLock(1);
        ReenterLock reenterLock2 = new ReenterLock(2);
        Thread t1 = new Thread(reenterLock1);
        Thread t2 = new Thread(reenterLock2);
        t1.start();t2.start();
        Thread.sleep(1000);
        t2.interrupt();
    }

}
